#include "VideoModuleState.h"
#include "MainLoopState.h"
#include "Portfolio.h"
#include <fstream>

VideoModuleState::VideoModuleState(string name) : ModuleState(name)
{
}

VideoModuleState::~VideoModuleState(void)
{
}

void VideoModuleState::enter()
{
	//Reset Mouse Wheel
	position_mouse_z(0);
	scare_mouse();

	//Generate Text for Game
	dataFileName = "PORT/VIDEO/" + name + "_G.dat";

	//Load Graphic file for the game
	port->getRMgr()->loadDataFile(dataFileName);

	//Read help text file
	helpFileName = "PORT/VIDEO/DOC/" + name + ".txt";
	char bufin[256];
	line = 0;
	fstream openf;
	openf.open(helpFileName.c_str(),ios::in);
	while (!openf.eof())
	{
		openf.getline(bufin, 256);
		strcpy(helpText[line++], bufin);
	}
	for(int i = 3; i < 256; i++)
	{
		helpText[0][i - 3] = helpText[0][i];
	}
	openf.close();
	openf.clear();

	submenubutton_pmask = create_allegro_pmask(
		(BITMAP *)port->getRMgr()->GraphicPackA[Submenubuttonpmask].dat);

	//Mouse hit detection image
	B_mousehit = create_bitmap(1,1);
	mousehit_pmask = create_allegro_pmask(B_mousehit);
}

void VideoModuleState::update(const float delta)
{

	checkMouse();
	if(state == 2)
	{
		if(mouselock == 1 && mouse_b == 1)
		{
			buttonroll = 0;
			state = 0;
			string exeDir = "PORT/VIDEO/";
			string cmdLine = "PORT/VIDEO/PLAYER.exe " + name + ".avi";
			startproc(const_cast<char *>(cmdLine.c_str()), const_cast<char *>(exeDir.c_str()));
		}
	}

	// If we are quiting save the back buffer for the fade out
	if (quit)
	{
		port->changeState(new MainLoopState());
	}
}
void VideoModuleState::render()
{
	port->getGUtil()->drawToBackBuffer(
		(BITMAP *)port->getRMgr()->GraphicPackA[Submenu].dat,
		0, 0);
	port->getGUtil()->drawToBackBuffer(
		(BITMAP *)port->getRMgr()->getData(0, dataFileName),
		50, 110);

	drawButtons(3);

	rect(port->getGUtil()->getLevel(0), 50, 110, 750, 510, C_ScrollBar);

	moduleTextHelp(buttonroll);

	//Mouse pointer dot
	rectfill(
		port->getGUtil()->getLevel(0),
		mouse_x - 3,
		mouse_y - 3,
		mouse_x + 3,
		mouse_y + 3,
		makecol(0,0,0));
	rectfill(
		port->getGUtil()->getLevel(0),
		mouse_x - 2,
		mouse_y - 2,
		mouse_x + 2,
		mouse_y + 2,
		makecol(255,255,255));

	port->getGUtil()->drawBackBufferToScreen();
	port->getGUtil()->clearBuffers();
}

void VideoModuleState::leave()
{
	destroy_pmask(mousehit_pmask);
	destroy_pmask(submenubutton_pmask);
	release_bitmap(B_mousehit);

	port->getRMgr()->unloadDataFile(dataFileName);
	clear_keybuf();

	port->getGUtil()->clearBuffers();
}